package com.liaoyin.travel.service.task;

import com.github.pagehelper.PageHelper;
import com.liaoyin.travel.vo.task.SelectTaskListVo;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.dao.task.TaskCompletionRecordMapper;
import com.liaoyin.travel.dao.task.TaskMapper;
import com.liaoyin.travel.dao.task.TaskReceivingRecordsMapper;
import com.liaoyin.travel.entity.BackUser;
import com.liaoyin.travel.entity.report.UserBriefing;
import com.liaoyin.travel.entity.task.Task;
import com.liaoyin.travel.entity.task.TaskCompletionRecord;
import com.liaoyin.travel.entity.task.TaskDetails;
import com.liaoyin.travel.entity.task.TaskReceivingRecords;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.back.BackUserService;
import com.liaoyin.travel.service.report.UserBriefingService;
import com.liaoyin.travel.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @项目名：旅投
 * @作者：lijing
 * @描述：任务领取记录
 * @日期：Created in 2018/6/20 14:55
 */
@Service
public class TaskReceivingRecordsService extends BaseService<TaskReceivingRecordsMapper, TaskReceivingRecords> {
   
	@Autowired
	public TaskService taskService;
	@Resource
	public TaskMapper taskMapper;
	@Autowired
	public TaskReceivingRecordsService taskReceivingRecordsService;
	@Autowired
	public TaskLineService taskLineService;
	@Autowired
	public UserBriefingService userBriefingService;
	@Autowired
	public BackUserService backUserService;
	@Resource
	public TaskCompletionRecordMapper taskCompletionRecordMapper;
	/*****
	 * 
	     * @方法名：insertTaskReceivingRecords
	     * @描述： 新增任务领取记录
	     * @作者： lijing
	     * @日期： 2019年7月15日
	 */
	public void insertTaskReceivingRecords(List<String> userList,String id) {
		
		List<TaskReceivingRecords> collect = userList.stream().map((u) ->{
			TaskReceivingRecords t = new TaskReceivingRecords();
			t.setCreatTime(new Date());
			t.setId(UUIDUtil.getUUID());
			t.setTaskId(id);
			t.setTastStatus((short)1);
			t.setUserId(u);
			return t;
		}).collect(Collectors.toList());
		if(collect !=null && collect.size() >0) {
			this.mapper.insertList(collect);
			collect = null;
			userList=null;
		}
	}
	
	/****
	 * 
	     * @方法名：updateTaskReceivingRecords
	     * @描述： 修改任务领取
	     * @作者： lijing
	     * @日期： 2019年7月15日
	 */
	public void updateTaskReceivingRecords(TaskReceivingRecords taskReceivingRecords) {
		
		if(taskReceivingRecords.getId() !=null && !"".equals(taskReceivingRecords.getId())){
			this.mapper.updateByPrimaryKeySelective(taskReceivingRecords);
		}else {
			//根据任务id，修改
			if(taskReceivingRecords.getTaskId()!=null && !"".equals(taskReceivingRecords.getTaskId())) {
				this.mapper.updateTaskReceivingRecords(taskReceivingRecords);
			}
		}
	}
	
	/****
	 * 
	     * @方法名：selectTaskReceivingRecordsByTaskId
	     * @描述： 根据任务id查询 任务领取记录
	     * @作者： lijing
	     * @日期： 2019年7月16日
	 */
	public List<TaskReceivingRecords> selectTaskReceivingRecordsByTaskId(String taskId,String userId,String tastStatus){
		
		 List<TaskReceivingRecords> list = this.mapper.selectTaskReceivingRecordsByTaskId(taskId, userId, tastStatus);
		 return list;
	}


	public List<TaskReceivingRecords> selectTaskReceivingRecordsByUserId(String userId,String tastStatus){

		return null;
	}
	
	/***
	 * 
	     * @方法名：selectTaskReceivingRecordsByTaskId
	     * @描述： 查询任务领取列表
	     * @作者： lijing
	     * @日期： 2019年8月26日
	 */
	public List<TaskReceivingRecords> selectTaskReceivingRecordsByTaskIdBack(SelectTaskListVo selectTaskListVo){
		
		if(selectTaskListVo == null) {
			throw new BusinessException("");
		}
		if(selectTaskListVo.getTaskId() == null) {
			throw new BusinessException("task.is.null");
		}
		/*if(selectTaskListVo.getTaskTime()== null || "".equals(selectTaskListVo.getTaskTime())) {
			selectTaskListVo.setTaskTime(DateUtil.getCurrentyyyyMMdd());
		}*/
		PageHelper.startPage(selectTaskListVo.getNum(),selectTaskListVo.getSize());
		List<TaskReceivingRecords> list = this.mapper.selectTaskReceivingRecordsByTaskIdBack(selectTaskListVo);
		for (TaskReceivingRecords records : list) {
			if (null != records.getNickName() && !"".equals(records.getNickName())){
				continue;
			} else {
				BackUser backUser = this.backUserService.selectBackUserById(records.getTempId());
				records.setNickName(backUser.getNickName());
			}
		}
		return list;
	}
	
	/****
	 * 
	     * @方法名：selectTaskReceivingRecordsdetailsById
	     * @描述： 查询任务领取详情
	     * @作者： lijing
	     * @日期： 2019年8月26日
	 */
	public Task selectTaskReceivingRecordsdetailsById(String id) {
		
		if(id == null) {
			throw new BusinessException("id.is.null");
		}
		TaskReceivingRecords t = this.mapper.selectByPrimaryKey(id);
		if(t == null) {
			throw new BusinessException("id.is.null");
		}
		Task task = this.taskService.selectById(t.getTaskId());
		if(task == null) {
			throw new BusinessException("task.is.null");
		}
		String s = this.taskMapper.selectNickNameByBackUser(task.getUserId());
		List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(task.getId(), t.getUserId(), null);
		task.setTaskReceivingRecords(taskReceivingRecords);
		List<UserBriefing> briefing = this.userBriefingService.getUserBriefingByTaskIdAndUserId(t.getTaskId(),t.getUserId());
		task.setUserBriefing(briefing.size() > 0 ? 0:1);
		if (null != briefing && briefing.size() > 0){
			task.setUserBriefingTime(briefing.get(0).getCreatTime());
		}
		if (s != null){
			task.setNickName(s);
		} else {
			String s1 = this.taskMapper.selectNickNameByUsers(t.getUserId());
			task.setNickName(s1);
		}
		if(task != null) {
			List<TaskDetails> list = this.taskLineService.selectTaskDetailsListByLineId(task.getLineId(), t.getUserId(),task.getTaskType() == 2 ? 0:1);
			for (TaskDetails details : list) {
				TaskCompletionRecord taskCompletionRecord = new TaskCompletionRecord();
				taskCompletionRecord.setTaskId(task.getId());
				taskCompletionRecord.setTaskDetailsId(details.getId());
				taskCompletionRecord.setTaskFlow(details.getTaskFlow());
				details.setTaskCompletionRecord((this.taskCompletionRecordMapper.selectOne(taskCompletionRecord)) == null ? null:this.taskCompletionRecordMapper.selectOne(taskCompletionRecord));
				taskCompletionRecord=null;
			}
			task.setTaskDetailsList(list);
			list = null;
		}
		
		return task;
	}

	/**
	　* @description: TODO  查询是否有执行的紧急任务
	　* @param [userId]
	　* @return boolean
	　* @throws
	　* @author privatePanda777@163.com
	　* @date 2019/8/29 16:09
	　*/
	public boolean selectTaskUrgentByUserId(String userId){
		boolean flag = false;
		List<TaskReceivingRecords> taskReceivingRecords = this.mapper.selectTaskUrgentByUserId(userId);
		if (taskReceivingRecords.size() > 0){
			flag = true;
		}
		return flag;
	}

	/**
	 * @方法名：selectTaskReceivingRecordsByTastStatus
	 * @描述： 按用户id(多个)和任务的状态查询任务领取记录
	 * @作者： Kuang.JiaZhuo
	 * @日期： Created in 2019/10/28 17:33
	 */
    public List<TaskReceivingRecords> selectTaskReceivingRecordsByTaskStatus(String userIds, int taskStatus) {
		List<String> userIdList = Arrays.asList(userIds.split(","));
		List<TaskReceivingRecords> list = this.mapper.selectTaskReceivingRecordsByTaskStatus(userIdList,taskStatus);
		return list;
    }

    /**
     * @方法名：selectTaskReceivingRecordsByWorkId
     * @描述： 返回指定的工种中人员按不同状态查询任务的领取记录
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/10/28 19:14
     */
	public List<TaskReceivingRecords> selectTaskReceivingRecordsByWorkId(String workIds, int taskStatus) {
		List<String> workIdList = Arrays.asList(workIds.split(","));
		List<TaskReceivingRecords> list = this.mapper.selectTaskReceivingRecordsByWorkId(workIdList,taskStatus);
		return list;
	}

	/**
	 * @方法名：insertTaskReceivingRecordsByUserIdAndTaskId
	 * @描述： 新增任务领取记录
	 * @作者： Kuang.JiaZhuo
	 * @日期： Created in 2019/11/12 22:11
	 */
	@Transactional(rollbackFor=BusinessException.class)
	public void insertTaskReceivingRecordsByUserIdAndTaskId(String taskId, String userId,String taskManagerId,String releaseWay,String scenicId) {
		Example example = new Example(TaskReceivingRecords.class);
		example.and().andEqualTo("userId",userId).andEqualTo("tastStatus",2);
		List<TaskReceivingRecords> taskReceivingRecordsList = this.taskReceivingRecordsService.selectByExample(example);
		for (TaskReceivingRecords receivingRecord : taskReceivingRecordsList) {
			String taskId1 = receivingRecord.getTaskId();
			Task task2 = this.taskMapper.selectByPrimaryKey(taskId1);
			if (task2.getTaskLevel() == 2){
//						throw new BusinessException("user.is.Busy");
			}else if (receivingRecord.getTastStatus() == 2 && task2.getTaskLevel() == 1 && task2.getTaskLevel() == 2){
				System.err.println("TaskBusinessService257="+taskId);
				tempTaskMap.put(taskId, receivingRecord.getId());
				receivingRecord.setTastStatus((short)4);
				taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
			}
		}
		TaskReceivingRecords taskReceivingRecords = new TaskReceivingRecords();
		taskReceivingRecords.setCreatTime(new Date());
		taskReceivingRecords.setId(UUIDUtil.getUUID());
		taskReceivingRecords.setTaskId(taskId);
		taskReceivingRecords.setTastStatus((short)1);
		taskReceivingRecords.setUserId(userId);
		taskReceivingRecords.setTaskManagerId(taskManagerId);
		taskReceivingRecords.setReleaseWay(releaseWay);
		System.err.println("scenicId="+scenicId);
		taskReceivingRecords.setScenicId(scenicId);
		this.mapper.insertSelective(taskReceivingRecords);
	}

	/**
	 * @方法名：countTaskReceivingRecordsByTaskId
	 * @描述： 统计任务领取人的数量
	 * @作者： kuang.jiazhuo
	 * @日期： Created in 2019/12/3 22:06
	 */
	public int countTaskReceivingRecordsByTaskId(String taskId) {
		int count = this.mapper.countTaskReceivingRecordsByTaskId(taskId);
		return count;
	}

	/**
	 * @方法名：updateTastStatusByTaskId
	 * @描述： 改变任务领取记录的状态
	 * @作者： kjz
	 * @日期： Created in 2020/4/7 15:59
	 */
	@Transactional(rollbackFor = Exception.class)
    public int updateTastStatusByTaskId(String taskId, short taskStatus) {
		TaskReceivingRecords taskReceivingRecords = new TaskReceivingRecords()
				.setTaskId(taskId).setTastStatus(taskStatus);
		return this.mapper.updateTaskReceivingRecords(taskReceivingRecords);
    }
}
